using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using SuperSocket;

namespace MSocketCore.MSocket
{
    public class MyMiddlewareBase : MiddlewareBase
    {
        private readonly ILogger _logger;

        private ISessionContainer _sessionContainer;
        private CancellationToken cancellationToken;
        private readonly CancellationTokenSource source = new CancellationTokenSource();

        public MyMiddlewareBase(ILogger<MiddlewareBase> logger)
        {
            _logger = logger;
        }

        public override void Start(IServer server)
        {
            _sessionContainer = server.GetSessionContainer();
            cancellationToken = source.Token;
            RunAsync();
        }

        private async Task RunAsync()
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(5000);
                _logger.LogWarning("Sessions : " + _sessionContainer.GetSessionCount());
            }
        }

        public override void Shutdown(IServer server)
        {
            source.Cancel();
        }
    }
}